﻿using Dapper;
using MangoMes.Commont.DapperHelps;
using MangoMes.Commont.Domain.RBACs;
using MangoMes.Commont.Domain.Suppliers;
using MangoMes.Commont.DTOs;
using MangoMes.Commont.Infrastructures.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using MySql.Data.MySqlClient;

namespace ManagoMes.Read.API.Applications.SupplierSearch
{
    public class SupplierSearchHandler : IRequestHandler<SupplierSearchCommand, PageDTO<SupplierDTO>>
    {
        private readonly IBateRepository<SupplierDTO> dro;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dro"></param>
        public SupplierSearchHandler(IBateRepository<SupplierDTO> dro)
        {
            this.dro = dro;
        }
        /// <summary>
        /// 供货商查询显示
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<PageDTO<SupplierDTO>> Handle(SupplierSearchCommand request, CancellationToken cancellationToken)
        {
            //分页查询
            PageDTO<SupplierDTO> pageDTO = new PageDTO<SupplierDTO>();
            var pageNum = (request.pageIndex-1)*request.pageSize;
            //连接数据库
            DapperHelper dapperHelper = new DapperHelper();
            string conn = dapperHelper.MangoMesRead;
            //实体DTO
            SupplierDTO sip = new SupplierDTO();
            string str = "select * from supplier " +
                        "inner join supplierclass on supplier.SupplierClassId=supplierclass.SupplierClassId where supplier.SupplierStart = 0";
            var result = dro.GetAll(str, sip, conn).ToList();
            if (!string.IsNullOrEmpty(request.SupplierNo))
            {
                result = result.Where(p => p.SupplierNo == request.SupplierNo).ToList();
            }
            if (!string.IsNullOrEmpty(request.SupplierName))
            {
                result = result.Where(p => p.SupplierName.Contains(request.SupplierName)).ToList();
            }
            if (!string.IsNullOrEmpty(request.SupplierShort))
            {
                result = result.Where(p => p.SupplierShort == request.SupplierShort).ToList();
            }
            if (!string.IsNullOrEmpty(request.SupplierEnglishName))
            {
                result = result.Where(p => p.SupplierEnglishName == request.SupplierEnglishName).ToList();
            }
            if (request.SupplierIsNo > -1)
            {
                result = result.Where(p => p.SupplierIsNo == request.SupplierIsNo).ToList();
            }

            pageDTO.TotalCount = result.Count();
            pageDTO.PageCount = (int)Math.Ceiling(result.Count() * 1.0 / request.pageSize);
            result = result.OrderBy(p=>p.SupplierId).Skip((request.pageIndex-1)*request.pageSize).Take(request.pageSize).ToList();
            pageDTO.Data = result;
            return pageDTO;
        }
    }
}
